//
//  SJImagePicker.m
//  TraderMobileKYi
//
//  Created by shijiezhao on 15/6/17.
//  Copyright © 2017年 com.yeezsoft.init. All rights reserved.
//

#import "SJImagePickerTool.h"

@implementation SJImagePickerTool




- (void)createImagePickerWithController:(UIViewController *)controller imagePickerType:(ImagePickerType)ImagePickerType imageBlock:(GainImageBlock)imageBlock
{
    self.gainImageBlock = imageBlock;
    
    // 创建相册控制器对象
    UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
    // 设置代理对象
    imagePickerVC.delegate = self;
    // 设置照片的编辑模式
    imagePickerVC.allowsEditing = YES;
    // 指定媒体类型
    // 1.获取相册里面的图片，2.获取相册里面的时候，3.打开照相机，4.打开录像机
    imagePickerVC.mediaTypes = @[@"public.image"];
    //    imagePickerVC.mediaTypes = @[@"public.image",@"public.movie"];
    // 设置类型
    if (ImagePickerType == 0)
    {
        // 设置为打开本地相册
        imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    else if (ImagePickerType == 1)
    {
        // 判断当前设备是否有摄像头
        if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear] || [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) {
            // 打开相机
            imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        else
        {
            // 打开失败提示

            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"打开失败" message:@"您的设备没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertVC addAction:alertAction];
            
            [controller presentViewController:alertVC animated:YES completion:nil];
            
            return;
        }
        
    }
    
    // 通过模态视图弹出相册控制器（因为系统的相册控制器是导航控制器）
    [controller presentViewController:imagePickerVC animated:YES completion:nil];

}


#pragma mark -- --------------------代理方法--------------------

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//    NSLog(@"选择图片:%@",info);
    // 获取点击的图片
    UIImage *image = info[UIImagePickerControllerEditedImage];

    // 返回图片
    if(self.gainImageBlock)
    {
        self.gainImageBlock(image);
    }

    // 关闭相册控制器
    [picker dismissViewControllerAnimated:YES completion:nil];

    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
